package business;

import org.apache.commons.lang3.StringUtils;

import utils.MessageUtils;
import bean.Message;

public class MessageHandler {

	public static Message convertTextToMessage(String text) {
		Message message = new Message();

		// sender
		String sender = MessageUtils.findWord(text, 0);
		if (sender.contains("!")) {
			sender = StringUtils.substringBefore(sender, "!");
		}
		message.setSender(sender.substring(1));

		// command or code handling
		String serverProtocol = MessageUtils.findWord(text, 1);
		if (StringUtils.isAlpha(serverProtocol)) {
			message.setCommand(serverProtocol);
		} else if (StringUtils.isNumeric(serverProtocol)) {
			message.setCode(Integer.valueOf(serverProtocol));
		}

		// receiver
		String receiver = MessageUtils.findWord(text, 2);
		if (receiver == null || receiver.equals(MessageUtils.NULL_CODE)) {
			message.setReceiver(null);
		} else {
			message.setReceiver(receiver);
		}

		// text
		int posText = text.indexOf(MessageUtils.TRAILING, 1);
		if (posText == -1) {
			posText = StringUtils.ordinalIndexOf(text, MessageUtils.SPACE, 3);
		}
		if (posText >= 0) {
			String foundText = text.substring(posText);
			if (StringUtils.isNotBlank(foundText)) {
				message.setText(foundText.substring(1));
			}
		}

		return message;

	}

	public static String processSendTextCommand(String text) {
		if (text.startsWith(MessageUtils.SLASH)) {
			text = text.substring(1);
		}
		return text;
	}

}
